<template>
  <div class='container'>
    <el-card class="box-card" style="margin: 10px">
      <!-- ---------------------------头部----------------------------------- -->
      <div class="clearfix" style="margin-bottom: 15px;">
        <span style="font-size: 12px; color: pink;">说明：目前支持学科和关键字条件筛选</span>
        <el-button @click="$router.push('new')" type="success" style="float: right; padding:8px 15px;" size="small">
          <i class="el-icon-edit"></i>
          新增试题
        </el-button>
      </div>
      <!-- ---------------------------表单筛选区域--------------------------------- -->
      <el-form :inline="true" ref='form'  :model="form"  size="small" label-width="80px" >
        <!-- 第一列------------------------------ -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select  placeholder="请选择" v-model="form.subjectID" @change="hSubjectChange">
                <el-option
                v-for="item in subjectsList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          <el-form-item label="试题类型" >
            <el-select  placeholder="请选择" clearable v-model="form.questionType">
              <el-option label="单选" value="1"></el-option>
              <el-option label="多选" value="2"></el-option>
              <el-option label="简答" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目备注">
            <el-input v-model="form.remarks"></el-input>
          </el-form-item>
          </el-col>
          <!-- 第二列---------------------------- -->
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select placeholder="请选择" v-model="form.catalogID">
                <el-option
                v-for="item in catalogList"
                :key="item.value"
                :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select placeholder="请选择" clearable v-model="form.difficulty">
                <el-option label="简单" value="1"></el-option>
                <el-option label="一般" value="2"></el-option>
                <el-option label="困难" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业简称">
              <el-input v-model="form.shortName"></el-input>
            </el-form-item>
          </el-col>
          <!-- 第三列----------------------------- -->
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select placeholder="请选择" clearable v-model="form.tags">
                <el-option
                v-for="(item, index) in tagsList"
                :key="index"
                :label="item.label"
                :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方向">
              <el-select placeholder="请选择" clearable v-model="form.direction">
                <el-option
                v-for="items in directions"
                :key="items"
                :label="items"
                :value="items">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市">
              <el-select class="city" placeholder="请选择" clearable  v-model="form.province" style="margin-right:8px;" @change="hTabCity">
                <el-option
                v-for="item in provinceList"
                :key="item"
                :label="item"
                :value="item"></el-option>
              </el-select>
              <el-select class="city" placeholder="请选择" clearable v-model="form.city">
                <el-option
                v-for="item in cityList"
                :key="item"
                :label="item"
                :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 第四列----------------------------- -->
          <el-col :span="6" >
            <el-form-item label="关键字" style="float:right;margin-right:0;">
              <el-input  placeholder="根据题干搜索" v-model="form.keyword"></el-input>
            </el-form-item>
            <el-form-item label="录入人" style="float:right;margin-right:0;">
              <el-select placeholder="请选择" clearable v-model="form.creatorID">
                <el-option
                v-for="item in creatorList"
                :key="item.id"
                :label="item.username"
                :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="float:right;margin-right:0;">
              <el-button size="small" @click="hClear">清除</el-button>
              <el-button type="primary" size="small" @click="hSearch">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- ----------------------------tab栏切换区域----------------------------- -->
      <el-tabs v-model="activeName" type="card" @tab-click="hTabChanges">
        <el-tab-pane label="全部" name='all'></el-tab-pane>
        <el-tab-pane label="待审核" name='0'></el-tab-pane>
        <el-tab-pane label="已审核" name='1'></el-tab-pane>
        <el-tab-pane label="已拒绝" name='2'></el-tab-pane>
      </el-tabs>
      <!-- 总数据提示条 -->
      <el-alert
        style="margin-bottom: 15px;"
        v-if="alertText !== ''"
        :title="alertText"
        type="info"
        show-icon
        :closable="false">
      </el-alert>
      <!-- ---------------------表格---------------------- -->
      <el-table
        :data="tableData"
        v-loading='isLoading'
        element-loading-text="给我一点时间"
        style="width: 100%">
        <el-table-column
          type="index"
          align='center'
          label="序号"
          width="60">
          <template slot-scope="scope">
            <span>{{(requestParameters.page - 1) * requestParameters.pagesize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="试题编号"
          width="120">
          <template slot-scope="scope">
            <span>{{scope.row.number}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="subject"
          label="学科"
          width="120">
        </el-table-column>
        <el-table-column
          prop="catalog"
          label="目录"
          width="120">
        </el-table-column>
        <el-table-column
          label="题型"
          width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.questionType==='1'">单选</span>
            <span v-else-if="scope.row.questionType==='2'">多选</span>
            <span v-else-if="scope.row.questionType==='3'">简答</span>
          </template>
        </el-table-column>
        <el-table-column
          label="题干"
          width="200">
          <template slot-scope="scope">
            <span v-html="scope.row.question"></span>
          </template>
        </el-table-column>
        <el-table-column
          label="录入时间"
          width="180">
          <template slot-scope="scope">
            <span>{{scope.row.addDate|dateFormate}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="难度"
          width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.difficulty==='1'">简单</span>
            <span v-else-if="scope.row.difficulty==='2'">一般</span>
            <span v-else-if="scope.row.difficulty==='3'">困难</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="creator"
          label="录入人"
          width="120">
        </el-table-column>
        <el-table-column
          label="审核状态"
          width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.chkState===0">待审核</span>
            <span v-else-if="scope.row.chkState===1">通过</span>
            <span v-else-if="scope.row.chkState===2">拒绝</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="chkRemarks"
          label="审核意见"
          width="120">
        </el-table-column>
        <el-table-column
          prop="chkUser"
          label="审核人"
          width="120">
        </el-table-column>
        <el-table-column
          label="发布状态"
          width="120">
          <template slot-scope="scope">
            <!-- <span v-if="scope.row.publishState === 0">下架</span>
            <span v-else-if="scope.row.publishState === 1">上架</span> -->
            <span v-if="scope.row.publishState===0 && scope.row.chkState===0 || scope.row.chkState===2">待发布</span>
            <span v-else-if="scope.row.publishState===0 && scope.row.chkState===1">已下架</span>
            <span v-else-if="scope.row.publishState===1 && scope.row.chkState===1">已发布</span>
          </template>
        </el-table-column>
        <el-table-column
          header-align='center'
          fixed="right"
          label="操作"
          width="200">
          <!-- disabled 是否禁用状态 -->
          <template slot-scope="scope">
            <el-button @click="hPreview(scope.row)" type="text" size="small">预览</el-button>
            <el-button @click="hCheck(scope.row.id)" type="text" size="small" :disabled= "scope.row.chkState ? true : false">审核</el-button>
            <el-button @click="hChange(scope.row.id)" type="text" size="small" :disabled= "scope.row.publishState ? true : false" >修改</el-button>
            <!-- <el-button @click="hChangePublishState(scope.row)" type="text" size="small" >{{scope.row.publishState === 0 ? '下架' : '上架'}}</el-button> -->
            <el-button type="text" size="small" disabled v-if="scope.row.chkState===null">上架</el-button>
            <el-button @click="hChangePublishState(scope.row)" type="text" size="small" v-else-if="scope.row.publishState===0 && scope.row.chkState===0 || scope.row.chkState===2">上架</el-button>
            <el-button @click="hChangePublishState(scope.row)" type="text" size="small" v-else-if="scope.row.publishState===0 && scope.row.chkState===1">上架</el-button>
            <el-button @click="hChangePublishState(scope.row)" type="text" size="small" v-else-if="scope.row.publishState === scope.row.chkState">下架</el-button>
            <el-button @click="hDelete(scope.row.id)" type="text" size="small" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- ------------------------页码------------------------- -->
      <el-pagination
        style="margin:20px 0; float:right;"
        background
        @size-change="hSizeChange"
        @current-change="hCurrentChange"
        :current-page="requestParameters.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="requestParameters.pagesize"
        layout="prev, pager, next, sizes, jumper"
        :total="total">
      </el-pagination>
      <!-- ------------------审核弹出对话框--------------------------- -->
      <el-dialog title="题目审核" :visible.sync="dialogFormVisible"  width="25%">
        <el-form :model="form" >
          <el-form-item >
              <el-radio v-model="form.chkState" label="1">通过</el-radio>
              <el-radio v-model="form.chkState" label="2">拒绝</el-radio>
          </el-form-item>
          <el-form-item>
            <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
            resize=none
            v-model="form.chkRemarks"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="hSubmitRemarks()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- ---------------------预览弹出对话框--------------------------- -->
      <el-dialog
        title="题目预览"
        :data="previewData"
        :visible.sync="dialogVisible"
        width="50%">
        <!-- **********第一块 信息类型************** -->
        <div class="details" >
          <el-row :gutter="10" style="padding: 10px 0;">
            <el-col :span="6">
              【题型】：<span v-if="previewData.questionType==='1'">单选题</span>
              <span v-else-if="previewData.questionType==='2'">多选题</span>
              <span v-else-if="previewData.questionType==='3'">简答题</span>
            </el-col>
            <el-col :span="6">【编号】：{{previewData.id}}</el-col>
            <el-col :span="6">
              【难度】：<span v-if="previewData.difficulty==='1'">简单</span>
              <span v-else-if="previewData.difficulty==='2'">一般</span>
              <span v-else-if="previewData.difficulty==='3'">困难</span>
            </el-col>
            <el-col :span="6">【标签】：{{previewData.tags}}</el-col>
          </el-row>
          <el-row :gutter="10" style="padding: 10px 0;">
            <el-col :span="6">【学科】：{{previewData.subject}}</el-col>
            <el-col :span="6">【目录】：{{previewData.catalog}}</el-col>
            <el-col :span="6">【方向】：{{previewData.direction}}</el-col>
          </el-row>
        </div>
        <hr>
        <!-- **********第二块 题干************** -->
        <div class="question">
          <div>【题干】：</div>
          <div v-html="previewData.question" style="color:blue;"></div>
          <!-- 如果试题类型为简答题  则隐藏下面的选项div -->
          <div v-if="(previewData.questionType==='3')? false : true">
            <div>
              <span v-if="previewData.questionType==='1'">单选题</span>
              <span v-else-if="previewData.questionType==='2'">多选题</span>
              <span v-else-if="previewData.questionType==='3'">简答题</span>
              选项：（ 以下选中的选项为正确答案 ）
            </div>
          <!-- 如果试题类型为单选题  则设置单选框组 对试题选项进行循环 -->
            <div v-if="previewData.questionType==='1'">
              <el-radio-group class="disable" v-model="radio">
                <el-radio
                style="display: block; padding: 10px 0;"
                v-for="item in optionList"
                :key="item.id"
                :label="item.isRight">
                {{item.title}}
                </el-radio>
              </el-radio-group>
            </div>
          <!-- 如果试题类型为多选题  则设置多选框组 对试题选项进行循环 -->
            <div v-else-if="previewData.questionType==='2'">
              <el-checkbox-group class="disable" v-model="checkList">
                <el-checkbox
                style="display: block; padding: 10px 0;"
                v-for="item in optionList"
                :key='item.id'
                :label="item.title">
                <!-- {{item.title}} -->
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <hr>
        <!-- **********第三块 参考答案************** -->
        <div class="videoURL">
          【参考答案】： <el-button type="danger" size="small" @click="hvideoShow(previewData.videoURL)">视频答案预览</el-button>
          <div class="video" style="margin-top: 20px;" v-show="isShow">
            <video :src="previewData.videoURL" controls='controls' autoplay="autoplay" width="300" height="200"></video>
          </div>
        </div>
        <hr>
        <!-- **********第四块 答案解析************** -->
          【答案解析】：<div class=" answer" style="display:inline-block;" v-html="previewData.answer"></div>
        <hr>
        <!-- **********第五块 题目备注************** -->
        <div class="remarks">
          【题目备注】：{{previewData.remarks}}
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" type="primary">关闭</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { choice, remove, choicePublish, choiceCheck, detail } from '@/api/hmmm/questions.js'
import { simple } from '@/api/hmmm/subjects.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { simple as sim } from '@/api/hmmm/directorys.js'
import { simple as usersim } from '@/api/base/users.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
export default {
  data () {
    return {
      // 预览对话框中单选选项默认选中答案
      radio: 1,
      // 预览对话框中多选选项默认选中答案
      checkList: [],
      // 答案解析视频显示状态
      isShow: false,
      // 当点击预览按钮时获取当前行的数据
      previewData: {},
      // 预览弹出框的状态
      dialogVisible: false,
      // 审核弹出框的状态
      dialogFormVisible: false,
      name: 'questionChoice',
      total: 0,
      isLoading: false,
      alertText: '', // 数据提示总条数
      requestParameters: {
        page: 1, // 当前页码
        pagesize: 5 // 每页多少条
      },
      form: {
        subjectID: null, // 学科
        catalogID: null, // 二级目录
        difficulty: '', // 难度
        questionType: '', // 试题类型
        tags: '', // 标签
        province: '', // 省份
        city: '', // 城市
        keyword: null, // 关键字
        remarks: '', // 题目备注
        enterpriseID: '',
        shortName: '', // 企业简称
        direction: '', // 方向
        creatorID: '', // 录入人
        chkState: '', // 审核状态
        chkRemarks: '' // 审核意见
      },
      subjectsList: [], // 学科数据
      catalogList: [], // 目录数据
      creatorList: [], // 录入人数据
      optionList: [], // 答案选项
      tagsList: [], // 标签数据
      State: null,
      activeName: 'all', // tab栏默认选择
      tableData: [], // 表格列表
      directions: [
        'o2o',
        '外包服务',
        '企业服务',
        '互联网金融',
        '企业咨询',
        '互联网',
        '电子商务',
        '其他'
      ],
      provinceList: [],
      cityList: [],
      // 校验审核意见
      // rules: {
      //   chkRemarks: [
      //     { required: true, message: '请输入审核意见', trigger: 'blur' }
      //   ]
      // },
      checkId: '', // 审核id
      previewId: '' // 预览id
    }
  },
  created () {
    // 渲染表格数据
    this.loadQuestions()
    // 获取学科列表
    this.getSubject()
    // 获取录入人列表
    this.getCreator()
    // 获取城市列表
    this.getCitys()
  },
  methods: {
    // 重置按钮
    hClear () {
      this.form = {}
      this.loadQuestions()
    },
    // 搜索按钮
    hSearch () {
      // console.log(this.form)
      this.requestParameters.page = 1
      this.loadQuestions()
    },
    // 发送请求获取列表数据
    async loadQuestions () {
      try {
        const query = {
          page: this.requestParameters.page,
          pagesize: this.requestParameters.pagesize,
          chkState: this.State,
          subjectID: this.form.subjectID,
          keyword: this.form.keyword,
          difficulty: this.form.difficulty,
          questionType: this.form.questionType,
          tags: this.form.tags,
          province: this.form.province,
          city: this.form.city,
          remarks: this.form.remarks,
          shortName: this.form.shortName,
          direction: this.direction,
          creatorID: this.form.creatorID,
          catalogID: this.form.catalogID
        }
        this.isLoading = true
        await choice(query).then((res) => {
          console.log('渲染的数据', res)
          // 获取数据给tableData
          this.tableData = res.data.items
          // 获取总条数
          this.total = res.data.counts
          this.alertText = `数据一共 ${res.data.counts} 条`
        }).catch((err) => {
          console.log(err)
        })
      } catch (err) {
        console.log(err)
      }
      // 改变加载状态值
      this.isLoading = false
    },
    // 获取学科列表
    async getSubject () {
      try {
        const res = await simple()
        // console.log(res)
        this.subjectsList = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取目录列表
    async getCatalogList () {
      const res = await sim()
      // console.log(res)
      this.catalogList = res.data
    },
    // 获取标签列表
    async getTagsList () {
      const res = await tagsSimple()
      // console.log('标签列表数据', res)
      this.tagsList = res.data
    },
    // 获取录入人列表
    async getCreator () {
      const res = await usersim()
      // console.log('用户简单列表数据', res)
      this.creatorList = res.data
    },
    // 获取省份城市列表
    async getCitys () {
      const res = await provinces()
      // console.log('省份列表', res)
      this.provinceList = res
    },
    // 学科下拉框选择时
    hSubjectChange (val) {
      // console.log(val)
      if (val) {
        // 获取目录列表
        this.getCatalogList()
        // 获取标签列表
        this.getTagsList()
      }
    },
    // 城市下拉框选择时
    hTabCity (val) {
      // 选中省份后 触发函数
      // console.log(val)
      if (val) {
        this.cityList = citys(val)
      } else {
        this.cityList = []
      }
      // console.log(this.cityList)
    },
    // 获取答案选项
    async getoptionList (id) {
      const res = await detail({ id })
      // console.log('获取试题答案的选项', res.data.options)
      this.optionList = res.data.options
      // 循环获取答案选项数组
      this.checkList = this.optionList.map(item => {
        if (item.isRight === 1) {
          return item.title
        }
      })
      // console.log(this.checkList)
    },
    // 点击切换tab栏
    async hTabChanges (tab, event) {
      // console.log(tab)
      // console.log(event)
      // console.log(Number(tab.name))
      if (this.activeName === 'all') {
        this.State = null
        this.loadQuestions()
      } else {
        this.State = Number(this.activeName)
        // this.tableData = this.tableData.filter(item => {
        //   return item.chkState === this.State
        // })
        // console.log(this.tableData) 如果这样写的话每次点击tab栏之后还要还原tableData里的数据
        this.requestParameters.page = 1
        this.loadQuestions()
      }
    },
    // 表格操作列
    hClick (row) {
      console.log(row)
    },
    // 每页条数改变时
    hSizeChange (size) {
      // console.log(size)
      this.requestParameters.pagesize = size
      this.requestParameters.page = 1
      this.loadQuestions()
    },
    // 当前页码变化时
    hCurrentChange (page) {
      // console.log(page)
      this.requestParameters.page = page
      this.loadQuestions()
    },
    // 列表预览功能----------------------------------------------------
    hPreview (data) {
      // 打开对话框
      this.isShow = false
      this.dialogVisible = true
      this.previewId = data.id
      // console.log(this.previewId)
      // 预览当前行的数据
      this.previewData = data
      // console.log(this.previewData)
      // 获取试题答案选项列表
      this.getoptionList(this.previewId)
    },
    // 视频答案预览功能
    hvideoShow (url) {
      // 注意：如果无视频连接，不打开播放器即可
      if (url !== '') {
        this.isShow = !this.isShow
      }
    },
    // 预览对话框关闭
    // hPreviewClose () {
    //   // 关闭对话框
    //   this.dialogVisible = false
    //   // 同时如果视频播放器是显示的状态的话 要记得关闭其显示 （以防下次打开其他行的预览时其自动显示）
    //   this.isShow = false
    // },
    // 列表审核功能----------------------------------------------------
    hCheck (id) {
      this.dialogFormVisible = true
      // 把id的值传给hSubmitRemarks函数 定义一个变量传值
      this.checkId = id
    },
    async hSubmitRemarks () {
      if (this.form.chkState === '' || this.form.chkRemarks === '') {
        return this.$message.warning('请输入审核意见')
      }
      this.dialogFormVisible = false
      const id = this.checkId
      try {
        // 获取参数
        const data = {
          id,
          chkState: Number(this.form.chkState), // 格式是整数
          chkRemarks: this.form.chkRemarks
        }
        // 发送请求 提交审核意见
        const res = await choiceCheck(data)
        console.log('提交审核意见', res)
        // 提示
        this.$message.success('操作成功')
        // 重新加载列表
        this.loadQuestions()
      } catch (err) {
        console.log(err)
      }
    },
    // 修改功能----------------------------------------------------
    hChange (id) {
      this.$router.push({
        path: 'new',
        query: {
          id
        }
      })
    },
    // 上下架功能---------------------------------------------------
    hChangePublishState (data) {
      // console.log(data.id)
      console.log(data.publishState) // 0 -下架状态   1 - 上架状态
      console.log(data.chkState)
      this.$confirm(`您确定${data.publishState === 1 && data.chkState === 1 ? '下架' : '上架'}这道题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          if (data.chkState === 1) {
            await choicePublish({
              id: data.id,
              publishState: data.publishState === 0 ? 1 : 0
            })
            // 查看请求的状态是否成功
            // console.log(res)
            this.loadQuestions()
            this.$message.success(`${data.publishState === 1 && data.chkState === 1 ? '下架' : '上架'}成功`)
          } else {
            this.$message.warning('请先通过审核')
          }
        } catch (err) {
          console.log(err)
          this.$message.error('操作失败')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 列表删除功能-------------------------------------------------
    hDelete (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await remove({ id })
        console.log(res)
        this.loadQuestions()
        this.$message.success('删除成功！')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  },
  // 时间格式化
  filters: {
    dateFormate (val) {
      const date = new Date(val)
      const y = date.getFullYear()
      const m = addZero(date.getMonth() + 1)
      const d = addZero(date.getDate())
      const h = addZero(date.getHours())
      const mm = addZero(date.getMinutes())
      const s = addZero(date.getSeconds())

      return y + '-' + m + '-' + d + '  ' + h + ':' + mm + ':' + s
      function addZero (r) {
        return (r < 10) ? '0' + r : r
      }
    }
  }
}
</script>

<style scoped lang='less'>
.container /deep/ .el-input--small .el-input__inner {
  width: 320px;
}
.city /deep/ .el-input--small .el-input__inner{
  width: 155px;
}
.container /deep/ .el-pagination .el-pagination__jump {
  margin-left: 0;
}
.container /deep/ .disable {
    pointer-events: none;
}
</style>
